<template>
  <div class="blog-container">
    <!-- 页面布局 -->
    <el-container class="layout-container">
      <!-- 左侧导航栏 -->
      <el-aside width="240px" class="sidebar-container">
        <div class="sidebar-header">
          <h2>博客导航</h2>
        </div>

        <el-menu
          default-active="category"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="category">
            <el-icon><folder-opened /></el-icon>
            <span>按类别浏览</span>
          </el-menu-item>
          <el-menu-item index="tag">
            <el-icon><PriceTag /></el-icon>
            <span>按标签浏览</span>
          </el-menu-item>

          <el-divider />

          <!-- 类别列表 -->
          <el-sub-menu index="categories" v-if="activeMenu === 'category'">
            <template #title>文章类别</template>
            <el-menu-item
              v-for="category in categories"
              :key="category.id"
              :index="category.id.toString()"
              @click="handleCategoryClick(category.id)"
            >
              {{ category.name }}
              <span class="category-count">{{ category.count }}</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 标签列表 -->
          <el-sub-menu index="tags" v-if="activeMenu === 'tag'">
            <template #title>文章标签</template>
            <el-menu-item
              v-for="tag in tags"
              :key="tag.id"
              :index="tag.id.toString()"
              @click="handleTagClick(tag.id)"
            >
              {{ tag.name }}
              <span class="tag-count">{{ tag.count }}</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 中间内容区 -->
      <el-container>
        <el-header class="main-header">
          <!-- 搜索框 -->
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索文章..."
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button
                  icon="Search"
                  @click="handleSearch"
                  class="search-button"
                />
              </template>
            </el-input>
          </div>
        </el-header>

        <el-main class="main-content">
          <!-- 文章列表 -->
          <div class="articles-container">
            <h3 class="articles-title">
              {{ currentTitle }}
              <span class="articles-count"
                >({{ filteredArticles.length }})</span
              >
            </h3>

            <el-empty
              v-if="filteredArticles.length === 0"
              description="没有找到匹配的文章"
              class="empty-articles"
            >
            </el-empty>

            <el-card
              v-for="article in filteredArticles"
              :key="article.id"
              class="article-card"
              hoverable
            >
              <div class="article-header">
                <h4 class="article-title">{{ article.title }}</h4>
                <span class="article-date">{{ formatDate(article.date) }}</span>
              </div>

              <div class="article-content">
                <p class="article-excerpt">{{ article.excerpt }}</p>
              </div>

              <div class="article-footer">
                <el-tag
                  class="article-category"
                  :type="getCategoryType(article.categoryId)"
                >
                  {{ getCategoryName(article.categoryId) }}
                </el-tag>

                <div class="article-tags">
                  <el-tag
                    v-for="tagId in article.tagIds"
                    :key="tagId"
                    size="small"
                    effect="plain"
                  >
                    {{ getTagName(tagId) }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </div>
        </el-main>
      </el-container>

      <!-- 右侧统计图表 -->
      <el-aside width="360px" class="chart-container">
        <el-card class="statistics-card">
          <el-tabs
            v-model="activeTab"
            class="statistics-tabs"
            @tab-change="handleTabChange"
          >
            <el-tab-pane label="类别统计" name="category-chart">
              <div class="chart-wrapper">
                <div class="chart-placeholder">
                  <p>类别统计图表</p>
                  <div v-for="(item, index) in categoryChartData" :key="index" class="chart-item">
                    <span>{{ item.name }}</span>
                    <el-progress :percentage="calculatePercentage(item.count)" :stroke-width="10" :color="getCategoryColor(item.name)" />
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="标签统计" name="tag-chart">
              <div class="chart-wrapper">
                <div class="chart-placeholder">
                  <p>标签统计图表</p>
                  <div v-for="(item, index) in tagChartData" :key="index" class="chart-item">
                    <span>{{ item.name }}</span>
                    <el-progress :percentage="calculatePercentage(item.count)" :stroke-width="10" :color="getTagColor(item.name)" />
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-aside>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from "vue";

// 图标
import {
  FolderOpened,
  PriceTag,
  Search,
  Document,
  Management,
} from "@element-plus/icons-vue";

export default {
  components: {
    FolderOpened,
    PriceTag,
    Search,
    Document,
    Management,
  },
  setup() {
    // 状态管理
    const activeMenu = ref("category"); // 左侧菜单激活项
    const activeTab = ref("category-chart"); // 右侧图表激活标签
    const searchKeyword = ref(""); // 搜索关键词
    const selectedCategoryId = ref(null); // 选中的类别ID
    const selectedTagId = ref(null); // 选中的标签ID

    // 文章类别数据
    const categories = ref([
     
    ]);

    // 模拟数据 - 标签
    const tags = ref([
      { id: 1, name: "Vue", count: 8 },
      { id: 2, name: "JavaScript", count: 10 },
      { id: 3, name: "Python", count: 6 },
      { id: 4, name: "React", count: 5 },
      { id: 5, name: "Node.js", count: 4 },
      { id: 6, name: "MySQL", count: 3 },
      { id: 7, name: "算法", count: 2 },
    ]);

    // 模拟数据 - 文章
    const articles = ref([
      {
        id: 1,
        title: "Vue.js 3.0 新特性",
        slug: "vue-3-0-new-features",
        summary: "Vue.js 3.0 新特性介绍",
        coverImage: "https://picsum.photos/200/300?random=1",
        content: "Vue.js 3.0 新特性介绍...",
        status: "published",
        commentStatus: "open",
        isTop: "0",
        metaData: "",
        publishedAt: "2023-05-01",
        categoryId: 1,
        tagIds: [1, 2],
        excerpt: "Vue.js 3.0 新特性介绍",
        date: "2023-05-01"
      },
    ]);





    // 处理菜单选择
    const handleMenuSelect = (index) => {
      activeMenu.value = index;
      // 重置选择
      selectedCategoryId.value = null;
      selectedTagId.value = null;
      searchKeyword.value = "";
    };

    // 处理类别点击
    const handleCategoryClick = (id) => {
      selectedCategoryId.value = id;
      selectedTagId.value = null;
      searchKeyword.value = "";
    };

    // 处理标签点击
    const handleTagClick = (id) => {
      selectedTagId.value = id;
      selectedCategoryId.value = null;
      searchKeyword.value = "";
    };

    // 处理搜索
    const handleSearch = () => {
      selectedCategoryId.value = null;
      selectedTagId.value = null;
    };

    // 处理标签页切换
    const handleTabChange = (tab) => {
      activeTab.value = tab;
    };

    // 获取过滤后的文章列表
    const filteredArticles = computed(() => {
      return articles.value.filter((article) => {
        // 类别过滤
        if (
          selectedCategoryId.value &&
          article.categoryId !== selectedCategoryId.value
        ) {
          return false;
        }

        // 标签过滤
        if (
          selectedTagId.value &&
          !article.tagIds.includes(selectedTagId.value)
        ) {
          return false;
        }

        // 搜索关键词过滤
        if (
          searchKeyword.value &&
          !article.title
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase()) &&
          !article.excerpt
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase())
        ) {
          return false;
        }

        return true;
      });
    });

    // 获取当前标题
    const currentTitle = computed(() => {
      if (searchKeyword.value) {
        return `搜索结果: "${searchKeyword.value}"`;
      }

      if (selectedCategoryId.value) {
        const category = categories.value.find(
          (c) => c.id === selectedCategoryId.value
        );
        return `类别: ${category ? category.name : "未知"}`;
      }

      if (selectedTagId.value) {
        const tag = tags.value.find((t) => t.id === selectedTagId.value);
        return `标签: ${tag ? tag.name : "未知"}`;
      }

      return activeMenu.value === "category" ? "所有类别文章" : "所有标签文章";
    });

    // 获取类别名称
    const getCategoryName = (id) => {
      const category = categories.value.find((c) => c.id === id);
      return category ? category.name : "未知";
    };

    // 获取标签名称
    const getTagName = (id) => {
      const tag = tags.value.find((t) => t.id === id);
      return tag ? tag.name : "未知";
    };

    // 获取类别样式
    const getCategoryType = (id) => {
      const category = categories.value.find((c) => c.id === id);
      return category ? category.color : "";
    };

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    };

    // 图表配置 - 类别统计
    const categoryAngleField = ref("count");
    const categoryColorField = ref("name");
    const categoryLabel = ref({
      position: "outside",
      formatter: (datum) => {
        return `${datum.name}: ${datum.count} (${Math.round(
          (datum.count / totalArticles.value) * 100
        )}%)`;
      },
    });

    // 图表配置 - 标签统计
    const tagAngleField = ref("count");
    const tagColorField = ref("name");
    const tagLabel = ref({
      position: "outside",
      formatter: (datum) => {
        return `${datum.name}: ${datum.count} (${Math.round(
          (datum.count / totalArticles.value) * 100
        )}%)`;
      },
    });

    // 总文章数
    const totalArticles = computed(() => {
      return articles.value.length;
    });

    // 类别图表数据
    const categoryChartData = computed(() => {
      return categories.value.map((category) => ({
        name: category.name,
        count: category.count,
      }));
    });

    // 标签图表数据
    const tagChartData = computed(() => {
      return tags.value.map((tag) => ({
        name: tag.name,
        count: tag.count,
      }));
    });

    // 添加计算百分比的方法
    const calculatePercentage = (count) => {
      if (totalArticles.value === 0) return 0;
      const percentage = Math.round((count / totalArticles.value) * 100);
      return Math.min(percentage, 100); // 确保百分比不超过100
    };
    
    // 添加获取类别颜色的方法
    const getCategoryColor = (name) => {
      const category = categories.value.find(c => c.name === name);
      const colorMap = {
        'primary': '#409eff',
        'success': '#67c23a',
        'warning': '#e6a23c',
        'info': '#909399',
        'danger': '#f56c6c'
      };
      return colorMap[category?.color] || '#409eff';
    };
    
    // 添加获取标签颜色的方法
    const getTagColor = (name) => {
      // 为标签生成颜色，可以使用固定颜色或根据名称生成
      const colors = ['#409eff', '#67c23a', '#e6a23c', '#909399', '#f56c6c'];
      const index = tags.value.findIndex(t => t.name === name);
      return colors[index % colors.length];
    };

    onMounted(() => {
      // 组件挂载时的初始化操作
    });

    return {
      // 数据
      activeMenu, // 当前激活的菜单项
      activeTab, // 当前激活的标签页
      searchKeyword, // 搜索关键词
      categories, // 类别列表
      tags, // 标签列表
      articles, // 文章列表
      filteredArticles, // 过滤后的文章列表
      currentTitle, // 当前标题
      // 方法
      handleMenuSelect, // 处理菜单选择
      handleCategoryClick, // 处理类别点击
      handleTagClick, // 处理标签点击
      handleSearch, // 处理搜索
      handleTabChange, // 处理标签页切换
      getCategoryName, // 获取类别名称
      getTagName, // 获取标签名称
      getCategoryType, // 获取类别样式
      formatDate, // 格式化日期
      // 图表数据
      categoryChartData, // 类别图表数据
      categoryAngleField, // 类别角度字段
      categoryColorField, // 类别颜色字段
      categoryLabel, // 类别标签
      // 标签数据
      tagChartData, // 标签图表数据
      tagAngleField, // 标签角度字段
      tagColorField, // 标签颜色字段
      tagLabel, // 标签标签
      // 添加新方法
      calculatePercentage,
      getCategoryColor,
      getTagColor
    };
  },
};

</script>

<style scoped>
.blog-container {
  height: 100vh;
  overflow: hidden; /* 隐藏整体滚动条，让各区域独立控制滚动 */
}

.layout-container {
  height: 100%;
}

/* 左侧导航栏样式 */
.sidebar-container {
  background-color: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto; /* 控制左侧导航区域的垂直滚动条 */
}

.sidebar-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
}

.sidebar-menu {
  width: 100%;
  border-right: none;
}

.category-count,
.tag-count {
  float: right;
  font-size: 12px;
  color: #86909c;
  background-color: #e5e6eb;
  border-radius: 10px;
  padding: 0 6px;
  margin-top: 2px;
}

/* 中间内容区样式 */
.main-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 24px;
}

.search-container {
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  height: 40px;
}

.search-button {
  background-color: #409eff;
  color: white;
}

.main-content {
  padding: 24px;
  overflow-y: auto; /* 控制中间内容区域的垂直滚动条 */
  background-color: #f2f3f5;
}

.articles-title {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
  color: #1f2329;
  display: flex;
  align-items: center;
}

.articles-count {
  font-size: 14px;
  color: #86909c;
  margin-left: 10px;
  font-weight: normal;
}

.article-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.article-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.article-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
  transition: color 0.2s;
}

.article-title:hover {
  color: #409eff;
}

.article-date {
  font-size: 12px;
  color: #86909c;
}

.article-excerpt {
  margin: 0 0 12px 0;
  color: #4e5969;
  font-size: 14px;
  line-height: 1.6;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.article-category {
  margin-right: 8px;
}

.article-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.empty-articles {
  margin: 40px 0;
}

.empty-icon {
  font-size: 48px;
  color: #c9cdd4;
}

/* 右侧图表区域样式 */
.chart-container {
  background-color: #f5f7fa;
  border-left: 1px solid #e4e7ed;
  padding: 16px;
  overflow-y: auto; /* 控制右侧图表区域的垂直滚动条 */
}

.statistics-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.statistics-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}

.chart {
  width: 100%;
  height: 300px;
}

.chart-placeholder {
  width: 100%;
  padding: 20px;
}

.chart-placeholder p {
  text-align: center;
  font-weight: bold;
  margin-bottom: 15px;
}

.chart-item {
  margin-bottom: 15px;
}

.chart-item span {
  display: block;
  margin-bottom: 5px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .chart-container {
    width: 300px;
  }
}

@media (max-width: 992px) {
  .sidebar-container {
    width: 200px !important;
  }

  .chart-container {
    width: 260px !important;
  }
}
</style>
